<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>POST发送ajax请求</button>
    <p></p>
    <script>
      let btn = document.querySelector('button');
        let p = document.querySelector('p');
        // 2. 给按钮添加点击事件
        btn.addEventListener('click', () => {
            let xhr = new XMLHttpRequest();
            xhr.open('post','http://localhost/postServer')

            // 设置请求头
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')

            // 用send发送请求体数据
            xhr.send('name=laowang&age=18');
            xhr.onreadystatechange = function(){
                // 4 完成
                if(xhr.readyState === 4){
                    // console.log(xhr.response);
                    p.innerHTML = xhr.response;
                }
            }
        })
    </script>
    </script>
</body>

</html>